angular.module("app.home")
    .directive("homeBtnAuth", ['loginService', function (loginService) {
        return {
            restrict: "A",
            link: function (scope, element, attrs) {

                var hasPermission = function (user, permission) {
                    for (var i = 0; i < user.permissions.length; i++) {
                        var p = user.permissions[i];
                        var resource = p.resource.toLowerCase();
                        var method = p.httpMethod.toLowerCase();
                        if (resource == permission) {
                            return true;
                        }
                        if (resource + method == permission) {
                            return true;
                        }
                    }
                    return false;
                };

                var checkPermission = function () {
                    $(".home Button").hide();
                    loginService.getUser().then(function (user) {
                        $(".home Button").each(function () {
                            var permissionsStr = $(this).data("btn-permission");
                            if (!permissionsStr) {
                                $(this).show();
                                return;
                            }

                            var permissions = permissionsStr.split(",");
                            for (var i = 0; i < permissions.length; i++) {
                                var permission = permissions[i];
                                if (hasPermission(user, permission)) {
                                    $(this).show();
                                    break;
                                }
                            }
                        });
                    });
                };

                checkPermission();

                scope.$on("permissionChanged", function (event, data) {
                    checkPermission();
                });
            }
        }
    }]);